<template>
  <el-card shadow="never" class="card_box">
    <div class="layout">
      <div class="top">
        <div class="title">详细数据</div>
      </div>
      <div>
        <el-form :inline="true" ref="searchRef" :model="params" class="detailTable">
          <div>
            <el-form-item label="客户姓名" prop="name">
              <el-input style="width: 300px" v-model="params.name" placeholder="请输入客户姓名进行搜索" />
            </el-form-item>
            <el-form-item>
              <el-button @click="search" type="primary">查询</el-button>
              <el-button @click="clear">清空</el-button>
            </el-form-item>
          </div>

          <el-form-item>
            <el-button :disabled="selectIds.length == 0" @click="handlBtn(1, 1, ['record_ids', 'assist_union_ids'])">批量核销</el-button>
            <el-button :disabled="selectIds.length == 0" @click="handlBtn(3, 1, ['record_ids', 'assist_union_ids'])">导出奖品</el-button>
            <el-button :disabled="selectIds.length == 0" @click="handlBtn(4, 1, ['record_ids', 'assist_union_ids'])">导出助力者</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-if="infoData.length > 0" :data="infoData" stripe style="width: 100%" @selection-change="handleSelectionChange" @sort-change="sortChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="客户信息" width="">
          <template #default="{ row }">
            <div class="cust">
              <el-image fit="cover" class="cust_avatar" :src="row.headimg">
                <template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span class="cust_name">{{ row.name || '--' }}</span>
              <img src="" alt="" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="participation_time" sortable="partTime" label="参与时间" width="" />
        <el-table-column prop="prize_num" sortable="winNum" label="中奖次数">
          <template #default="{ row }">
            <span>{{ row.prize_num }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="assist_num" sortable="assistNum" label="助力人数">
          <template #default="{ row }">
            <div @click="openWin(row, 2)" style="color: #fe292b"> {{ row.assist_num }} </div>
          </template>
        </el-table-column>
        <el-table-column>
          <template #header>
            <p class="table_label">
              <span>是否限制</span>
              <el-popover placement="top" width="auto" trigger="hover">
                <template #reference>
                  <img class="ques_icon" src="@/assets/smartMarketing/drainage/luckyDraw/question.png" alt="" />
                </template>
                <template #default>
                  <span> 开启后用户无法进行参与活动 </span>
                </template>
              </el-popover>
            </p>
          </template>
          <template #default="{ row }">
            <div>
              <el-switch @change="changeStatus(row)" v-model="row.limit_state" :active-value="2" :inactive-value="1" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200px">
          <template #default="{ row }">
            <div>
              <el-button size="small" @click="openWin(row, 1)">中奖记录</el-button>
              <el-button size="small" @click="handlBtn(7, 2, [], row)">客户详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="no_data" v-if="infoData.length == 0">
        <img class="no_img" src="@/assets/noData.png" alt="" />
        <div class="no_title">暂无数据</div>
      </div>
      <ZWPagination @submit="getPage"></ZWPagination>
    </div>
  </el-card>

  <el-drawer :destroy-on-close="true" v-model="dialog" :title="drawerTitle" direction="rtl" size="42%">
    <header>
      <p class="cust_info">
        <el-image fit="cover" class="avatar" :src="cust_info?.headimgurl">
          <template #error>
            <div class="image-slot">
              <el-icon><icon-picture /></el-icon>
            </div>
          </template>
        </el-image>
        <span class="name">{{ cust_info?.name ? cust_info?.name : cust_info?.nickname || '--' }}</span>
        <img v-show="cust_info?.sex == 1" class="sex" src="/static/employeetasks/male.png" alt="" />
        <img v-show="cust_info?.sex == 2" class="sex" src="/static/employeetasks/female.png" alt="" />
        <img v-show="cust_info?.sex == 0" class="sex" src="/static/employeetasks/noSex.png" alt="" />
      </p>
      <div class="record_info">
        <p
          >中奖次数：<span>{{ cust_info?.win_num }}</span></p
        >
        <p
          >助力人数：<span>{{ cust_info?.assist_num }}</span></p
        >
        <p
          >参与活动时间：<span>{{ cust_info?.participation_time }}</span></p
        >
      </div>
    </header>
    <ZwTable ref="tableRef" class="table-box tableClass" :option="tableOption" :fetch-params="state.searchParams" :fetch-api="fetchApi()" @dataChange="dataChange" @selection-change="onSelectionChange">
      <template #headerOperate>
        <el-button size="small" v-show="listType == 1" @click="handlBtn(2, 2, ['union_ids', 'assist_union_ids'], checkedArr)" :disabled="checkedArr.length <= 0">批量核销</el-button>
        <el-button size="small" v-show="listType == 1" :disabled="checkedArr.length <= 0" @click="handlBtn(5, 1, ['union_ids', 'assist_union_ids'], checkedArr)">导出</el-button>
        <el-button size="small" v-show="listType != 1" :disabled="checkedArr.length <= 0" @click="handlBtn(6, 1, ['record_ids', 'record_ids'])">导出</el-button>
      </template>
    </ZwTable>
  </el-drawer>
</template>

<script lang="tsx" setup>
import { reactive, ref, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import ZWPagination from '@/components/ZWPagination.vue'

import { channelDials } from '@/api/smartMarketing/drainage/channelCode/index'
import { update, winReceive, winRecord, assistRecord, prizeRecord, assist } from '@/api/smartMarketing/newLottery'
import { ElMessage, ElMessageBox, ElImage, ElIcon, ElButton } from 'element-plus'

import ZwTable from '@/components/zw/table/Table'
import { getSetionId } from '@/utils/utils'
import { deepCopy } from '@/utils/helper'

defineProps(['infoData', 'dataInfos'])
const router = useRouter()
const route = useRoute()
const searchRef = ref()
const tableRef = ref()
const cust_info = ref()
const activeId = ref(route.query.id)
const drawerTitle = ref('')
const dialog = ref(false)
let selectIds = ref([])
let checkedArr = ref([])
let checkedArr2 = ref([])
const listType = ref()

const defaultParams = reactive({
  // cust_id: '',
  activity_id: activeId.value,
  union_ids: []
})
const state = reactive({
  searchParams: deepCopy(defaultParams)
})
const tableOption = reactive([
  {
    type: 'selection',
    width: 55,
    fixed: 'left'
  },
  {
    label: '奖品信息',
    render({ row }) {
      const slotError = () => (
        <div class="image_slot">
          <ElIcon>
            <IconPicture />
          </ElIcon>
        </div>
      )
      return (
        <div class="cust_info">
          <ElImage class="avatar" src={row.img ? row.img : row.headimgurl} vSlots={{ error: slotError }} fit="cover"></ElImage>
          <span class="name" style="width: 30px, text-overflow: ellipsis,  white-space: nowrap,overflow: hidden">
            {row.name}
          </span>
          <img vShow={row.sex == 1} class="sex" src="/static/employeetasks/male.png" alt="" />
          <img vShow={row.sex == 2} class="sex" src="/static/employeetasks/female.png" alt="" />
          <img vShow={row.sex == 0} class="sex" src="/static/employeetasks/noSex.png" alt="" />
        </div>
      )
    }
  },
  {
    prop: 'prize_time',
    label: '中奖时间',
    width: 200
  },
  {
    prop: 'operate',
    label: '操作',
    width: 110,
    isOperate: true,
    render({ row, column, index }) {
      return (
        <>
          <ElButton vShow={listType.value == 1 && row.reward_type != 2 && row.verification_status == 1} size="small" onClick={() => handlBtn(2, 2, ['union_ids', 'assist_union_ids'], [row])}>
            核销
          </ElButton>
          <ElButton vShow={listType.value == 1 && row.reward_type != 2 && row.verification_status == 2} size="small" disabled>
            已核销
          </ElButton>
          <span vShow={listType.value == 1 && row.reward_type === 2}>--</span>
          <ElButton vShow={listType.value != 1} size="small" onClick={() => handlBtn(7, 2, ['union_ids'], row)}>
            客户详情
          </ElButton>
        </>
      )
    }
  }
])
const onSelectionChange = (data: any) => {
  // checkedArr.value = getSetionId('unionid', data)
  checkedArr.value = data
  checkedArr2.value = getSetionId('reward_id', data)
}
// 获取表格高度
const getTableH = () => {
  nextTick(() => {
    tableRef.value.getTableH()
  })
}
const fetchApi = () => {
  // 获取文件列表
  getTableH()
  return listType.value == 1 ? prizeRecord : assist
}
const dataChange = (res: any) => {
  cust_info.value = res.cust_info
}

const formInline = reactive({
  user: '',
  region: ''
})
let params = reactive({
  sort_by: '',
  sort: '',
  name: '',
  page: 1,
  page_size: 15
})
const emit = defineEmits({
  exportData: null,
  SortData: null
})
const exportData = () => {
  emit('exportData')
}
//升降序排列
const sortChange = (obj: any) => {
  if (obj.order === 'ascending') {
    params.sort = 'desc'
  }
  if (obj.order === 'descending') {
    params.sort = 'asc'
  }
  if (obj.prop === null && obj.order === null) {
    params.sort_by = ''
    params.sort = ''
  } else {
    params.sort_by = obj.column.sortable
  }
  emit('SortData', params)
}

const search = () => {
  emit('SortData', params)
}
const clear = () => {
  if (!searchRef.value) return
  searchRef.value.resetFields()
  emit('SortData', params)
}

const handleSelectionChange = (val: any) => {
  // selectIds.value = getSetionId('cust_id', val)
  selectIds.value = val
}

const verification = (p: any) => {
  ElMessageBox.confirm('确定核销当前奖品吗？', '核销提醒', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(() => {
      winReceive(p).then(() => {
        ElMessage.success('核销成功！')
        selectIds.value = []
        checkedArr.value = []
        if (p.type == 1) emit('SortData', params)
        else tableRef.value.reload()
      })
    })
    .catch(() => {})
}
const exportPrize = (exportType: number, exportParams: any) => {
  if (exportType == 1) {
    winRecord(exportParams).then((res: any) => {
      emit('SortData', params)
      window.location.href = res.url
    })
  } else {
    assistRecord(exportParams).then((res: any) => {
      emit('SortData', params)
      window.location.href = res.url
    })
  }
}

const filterParams = (vType: number, strArr: any, getId: string, selectVal: any) => {
  const res = {
    activity_id: activeId.value,
    type: vType,
    union_ids: getSetionId(getId, selectVal),
    record_ids: getSetionId(getId, selectVal),
    assist_union_ids: getSetionId(getId, selectVal)
  }
  strArr.map((item: any) =>
    Object.keys(res).reduce((ret, key) => {
      if (key == item) delete res[key]
    }, {})
  )
  return res
}

const handlBtn = (type: number, vType: number, strArr: any, row?: any) => {
  switch (type) {
    case 1:
      verification(filterParams(vType, strArr, 'unionid', selectIds.value))
      break
    case 2:
      verification(filterParams(vType, strArr, 'activity_record_id', row))
      break
    case 3:
      const winRes = filterParams(vType, strArr, 'unionid', selectIds.value)
      exportPrize(1, winRes)
      break
    case 4:
      const assinRes = filterParams(1, strArr, 'unionid', selectIds.value)
      exportPrize(2, assinRes)
      break
    case 5:
      const winRes2 = filterParams(2, strArr, 'activity_record_id', row)
      exportPrize(1, winRes2)
      break
    case 6:
      const assinRes2 = filterParams(2, strArr, 'unionid', checkedArr.value)
      exportPrize(2, assinRes2)
      break
    case 7:
      if (row.cust_id == 0) {
        ElMessage.warning('此客户不是我们客户')
        return
      }
      router.push({ path: '/customer/manage/list/detail?id=1859', query: { id: row.cust_id, type: 1} })
      break
  }
}

const getPage = (data: any) => {
  params.page = data.page
  params.page_size = data.page_size
  emit('SortData', params)
}

const changeStatus = (row: any) => {
  const res = {
    id: row.id,
    state: row.limit_state == 1 ? 1 : 2
  }
  update(res).then(() => {
    ElMessage.success('操作成功！')
    emit('SortData', params)
  })
}
const spliceList = (text: string, isAdd: number) => {
  const index = tableOption.findIndex((item: any) => item.label == text)
  if (isAdd == 1 && index != -1) {
    tableOption[1].label = '奖品信息'
    tableOption.splice(index, 1, {
      prop: 'prize_time',
      label: '中奖时间',
      width: 280
    })
  } else if (isAdd == 2 && index != -1) {
    tableOption[1].label = '助力者信息'
    tableOption.splice(index, 1, {
      prop: 'assist_time',
      label: '助力时间',
      width: 280
    })
  }
}

const openWin = (row: any, type: number) => {
  state.searchParams.union_ids = [row.unionid]
  dialog.value = true
  checkedArr.value = []
  listType.value = type
  spliceList(type == 1 ? '助力时间' : '中奖时间', type)
  drawerTitle.value = type == 1 ? '中奖记录' : '助力者列表'
}
defineExpose({
  search,
  params
})
</script>
<style lang="scss" scoped>
.card_box {
  margin-top: 16px;
}
.detailTable {
  display: flex;
  align-content: center;
  justify-content: space-between;
  margin: 16px 0;
}

.layout {
  background-color: #fff;
  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 16px;
    border-bottom: 1px solid #eaeaea;

    .title {
      font-size: 16px;
    }
  }
  .detail {
    &_btn {
      display: inline-block;
      padding: 5px 16px;
      border: 1px solid #eaeaea;
    }
  }
  .cust {
    display: flex;
    align-items: center;
    &_avatar {
      width: 24px;
      height: 24px;
      margin-right: 8px;
    }
  }
  .table_label {
    display: flex;
    align-items: center;
    .ques_icon {
      width: 16px;
      height: 16px;
      margin-left: 4px;
    }
  }
  .no_data {
    height: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .no_img {
      margin-left: 24px;
    }
    .no_title {
      color: #909399;
      font-size: 14px;
    }
  }
}
.tableClass {
  margin-top: 24px;
}
:deep .cust_info {
  display: flex;
  align-items: center;
  .avatar {
    width: 24px;
    height: 24px;
    border-radius: 4px;
  }
  .name {
    font-size: 14px;
    font-weight: 300;
    color: #33302d;
    line-height: 14px;
    margin: 0 4px 0 8px;
  }

  .sex {
    width: 14px;
    height: 15px;
  }
}
.record_info {
  font-size: 14px;
  font-family: STHeitiSC-Light, STHeitiSC;
  font-weight: 300;
  color: #969696;
  line-height: 20px;
  margin-top: 12px;
  padding-bottom: 24px;
  border-bottom: 1px solid #eaeaea;
  span {
    color: #33302d;
  }
}
:deep(.name_text) {
  display: inline-block;
  width: 30px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
</style>
